<template>
  <el-card style="margin-bottom: 30px">
    <template #header>
      <el-button
        type="primary"
        size="default"
        :icon="Plus"
        @click="addTrademark"
      >添加</el-button>
    </template>
<!--    弹出框的位置-->
    <el-dialog v-model="dialogFormVisible" :title="newTrademark.id?'修改品牌':'添加品牌'">
      <el-form :model="newTrademark" :rules="rules" ref="newTrademarkRules">
        <el-form-item label="品牌名称" :label-width="formLabelWidth" prop="tmName">
          <el-input v-model="newTrademark.tmName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="品牌logo" :label-width="formLabelWidth" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${baseUrl}/admin/product/upload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="newTrademark.logoUrl" :src="newTrademark.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="addOrUpdateTrademark"
        >确认</el-button
        >
      </span>
      </template>
    </el-dialog>
<!--    弹出框结束位置-->
    <el-table :data="tableData" stripe border>
      <el-table-column align="center" type="index" label="序号"></el-table-column>
      <el-table-column label="品牌名称" prop="tmName"></el-table-column>
      <el-table-column label="品牌logo" prop="logoUrl">
        <template #default="{row}">
          <el-image  :src="row.logoUrl" :style="{height:'150px'}" :lazy="lazy"/>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{row}">
          <el-button type="warning" size="small" :icon="Edit" @click="updateTrademark(row)">修改</el-button>
          <el-button type="danger" size="small" :icon="Delete" @click="deleteTrademark(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <el-pagination
    background
    v-model:page-size="limit"
    v-model:current-page="page"
    :total="total"
    :page-sizes=[3,5,7,9]
    layout="sizes,prev,pager,next,jumper"
  />
</template>

<script lang="ts">

import {defineComponent} from 'vue';

//page数据类型
export interface pageParamsType {
  page:number,
  limit:number,
  total:number,
}

export default defineComponent({
  name: 'Trademark',
});

</script>
<script setup lang="ts">
import {Plus, Edit, Delete } from '@element-plus/icons';
import {ref, toRefs, onMounted, watch} from 'vue';
import {
  reqTrademarkList,
  reqAddTrademark,
  reqDeleteTrademark,
  reqUpdateTrademark
} from '@/api/tradmark';
import { ElMessage , ElMessageBox} from 'element-plus'
import type {trademarkListType ,returnTrademarkItemType} from '@/api/tradmark'
import type { UploadProps , FormRules , FormInstance} from 'element-plus'

onMounted(()=>{
  getTrademarkList()
})
//图片懒加载
const lazy = ref(true)
//表单验证
const rules = ref<FormRules>({
  tmName:[
    {required:true, message: '品牌名称为必填选项', trigger: 'blur' },
    {min: 1 , max: 5, message: 'Length should be 3 to 5', trigger: 'blur'}
  ],
  logoUrl:[
    {required:true,message:'图片为必填选项',trigger:'change'}
  ]
})
const newTrademarkRules = ref<FormInstance>()
//设置页码参数需求
const pageParams = ref<pageParamsType>({
  page : 1,
  limit: 5,
  total: 100
})
const { page , limit , total} = toRefs(pageParams.value)
//表格静态数据
const tableData = ref<trademarkListType>([]);
//开始发送请求获取数据
const getTrademarkList = async () =>{
  try {
    const re = await reqTrademarkList({page:page.value,limit:limit.value})
    tableData.value = re.records
    total.value = re.total
    // console.log(tableData.value);
  }catch (e){
    ElMessage.warning((e as any).message)
  }
}
//监听页面的变化重新请求数据
watch([page,limit],()=>{
  getTrademarkList()
})
//点击添加按钮弹框,然后添加新的数据
//设置弹出框
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
const newTrademark = ref<returnTrademarkItemType>({
  tmName: '',
  logoUrl: '',
  id : 0
})
const baseUrl = import.meta.env.VITE_API_URL
//复制过来的上传图片的方法
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response
  // uploadFile
) => {
  // console.log('res',response);
  // console.log('upload',uploadFile);
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  newTrademark.value.logoUrl = response.data
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
//添加逻辑
const addTrademark = () => {
  //重新打开弹窗的时候清楚上一次的校验规则
  newTrademarkRules.value?.clearValidate()
  dialogFormVisible.value = true;
  newTrademark.value = {
    logoUrl: "",
    tmName: "",
    id: 0,
  };
};

//修改逻辑
const updateTrademark = async (row: returnTrademarkItemType) => {
  //重新打开弹窗的时候清楚上一次的校验规则
  newTrademarkRules.value?.clearValidate()
  dialogFormVisible.value = true;
  //获取当前的数据然后进行回填数据
  //拿到当前的数据浅拷贝赋值给表单的数据newTrademark(为了数据不会互相影响)
  newTrademark.value = { ...row };
};
//设置点击确定，之后更改数据，判断是添加还是更新

const addOrUpdateTrademark = async () => {
  dialogFormVisible.value = false
  try {
    await newTrademarkRules.value?.validate()
    //还是通过是否存在id来判断是添加还是更新
    try {
      if (newTrademark.value.id){
        await reqUpdateTrademark(newTrademark.value)
        ElMessage.success('修改成功')
      }else {
        await reqAddTrademark(newTrademark.value)
        ElMessage.success('添加成功')
      }
    }catch (e){
      ElMessage.error((e as any).message)
    }
  }catch (e){
    ElMessage.error('请添加合法的值！！！')
  }
  getTrademarkList()
}
//删除逻辑
const deleteTrademark = (id:number) => {
  ElMessageBox.confirm(
    '你确定要删除这一条数据么',
    '删除提醒',
    {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error',})
    .then(async () => {
      try {
        await reqDeleteTrademark(id)
        await getTrademarkList()
      }catch (e){
        ElMessage.error('删除失败',(e as any))
      }
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '你已经取消了删除',
      })
    })
}

</script>

<style scoped>

</style>
<style scoped>
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
